﻿using MediatR;
using SmartProduction.Domain.yjh;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.WorkNum;

namespace SmartProduction.Read.API.Application.CommandHandlers.WorkNum
{
    /// <summary>
    /// 工序管理查询命令处理
    /// </summary>
    public class WorkNumQueryCommandHandler:IRequestHandler<WorkNumQueryCommand,APIResult<APIPaing<Domain.yjh.Process>>>
    {
        private readonly IBaseRepository<Process> processrep;

        public WorkNumQueryCommandHandler(IBaseRepository<Domain.yjh.Process> processrep)
        {
            this.processrep = processrep;
        }

        public async Task<APIResult<APIPaing<Process>>> Handle(WorkNumQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaing<Process>> result = new APIResult<APIPaing<Process>>();

            var list = processrep.GetAll().Result.Where(x => x.IsDeleted == false);

            if (!string.IsNullOrEmpty(request.ProcessName))
            {
                list = list.Where(x => x.ProcessName.Contains(request.ProcessName));
            }
            if (!string.IsNullOrEmpty(request.IsStatus))
            {
                list = list.Where(x => x.IsStatus.ToString()==request.IsStatus);
            }
            int totalcount=list.Count();
            int totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.size);

            var pagelist = list.OrderByDescending(x => x.ProcessId).Skip((request.index - 1) * request.size).Take(request.size);

            APIPaing<Process> aPIPaing = new APIPaing<Process>();
            aPIPaing.TotalCount = totalcount;
            aPIPaing.PageCount= totalpage;

            aPIPaing.Items = pagelist.ToList();

            result.data=aPIPaing;

            return await Task.FromResult(result);
        }
    }
}
